<?php

namespace app\admin\controller\lal;
use app\common\controller\Backend;
use app\admin\library\Auth;
use Exception;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Db;
use think\db\exception\BindParamException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 拉卡拉账号管理
 *
 * @icon fa fa-circle-o
 */
class Member extends Backend
{

    /**
     * Member模型对象
     * @var \app\admin\model\lal\Member
     */
    protected $model = null;
    protected $info_model = null;
    protected $bank_model = null;
    protected $store_shop_model = null;
    protected $service_model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\lal\Member;
        $this->info_model = new \app\admin\model\lal\MemberInfo;
        $this->bank_model = new \app\admin\model\lal\Bank;
        $this->store_shop_model = new \app\admin\model\store\Shop;
        $this->service_model = new \app\admin\model\service\Service;
        $this->view->assign("typeList", $this->model->getTypeList());
        // print_r($this->model->getTypeList());die;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];

        return json($result);
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }

            if ($params['type'] == 0) {
                $shop_info = $this->store_shop_model->find($params['shop_id']);
                $params['shopname'] = empty($shop_info)?'':$shop_info['shopname'];
            }else{
                $shop_info = $this->service_model->find($params['shop_id']);
                $params['shopname'] = empty($shop_info)?'':$shop_info['name'];
            }

            $out_member_no = time().rand(100000, 999999);

            //发送会员开户请求，获取链接
            $req_params = [];
            $req_params['out_member_no'] = $out_member_no;
            $req_params['open_part'] = 1;
            $req_params['back_url'] = cdnurl('/api/Member/syncmember',true);
            $req_params['member_category'] = 0;
            $req_params['member_role'] = 'R001';
            $req_params['member_type'] = 3;
            $req_url = cdnurl('/api/Pay/addUser',true);
            write_log_record("[".date("Y-m-d H:i:s")."]会员开户req_url：".$req_url);
            write_log_record("[".date("Y-m-d H:i:s")."]会员开户参数：".json_encode($req_params,true));
            $result = send_request($req_url, $req_params,'GET');
            write_log_record("[".date("Y-m-d H:i:s")."]会员开户结果：".json_encode($result,true));   
            if ($result && !empty($result)) {
                if ($result['data']['status'] == 'OK' && isset($result['data']['result']['url']) && !empty($result['data']['result']['url'])) {
                    $params['url'] = $result['data']['result']['url'];
                }
            }
            
            $lal_id = $this->info_model->insertGetId(['out_member_no'=>$out_member_no,'createtime'=>time()]);
            if (!$lal_id || empty($lal_id)) {
                Db::rollback();
                $this->error('门店添加失败，请稍后重试！');
            }
            $params['lal_id'] = $lal_id;
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function getshoptypeList()
    {
        $params = $this->request->param();
        $type = isset($params['type'])?$params['type']:1;
        $page = $this->request->request('pageNumber')?:1;

        $limit = 10;
        $pagesize = ($page-1)*$limit;


        $return_data = ['list'=>[],'count'=>0];
        $list = [];
        $condition = ['status'=>'normal'];
        if ($type == 1) {
            $total = $this->store_shop_model->where($condition)->count();
            $list = $this->store_shop_model
                    ->field('id,shopname')
                    ->where($condition)
                    ->order('weigh desc,id desc')
                    ->limit($pagesize,$limit)
                    ->select();
        }else{
            $total = $this->service_model->where($condition)->count();
            $list = $this->service_model
                    ->field('id,name as shopname')
                    ->where($condition)
                    ->order('id desc')
                    ->limit($pagesize,$limit)
                    ->select();
        }

        return ['list'=>$list,'total'=>$total];
    }

    /**
     * 详情
     */
    public function detail($ids = null){
        if ($this->request->isPost()) {
            $this->token();
        }

        $row = $this->model->get($ids);

        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $this->assign('row',$row);
        return $this->view->fetch();
    }

    public function syncbankaccount($ids = null)
    {
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $row = $this->model->find($ids);

        if (empty($row) || empty($row['lal_id'])) {
            $this->error(__('No Results were found'));
        }

        $lal_member_info = $this->info_model->where(['id'=>$row['lal_id']])->find();
        if (empty($lal_member_info) || empty($lal_member_info['member_no'])) {
            $this->error(__('No Results were found'));
        }

        //发送会员开户请求，获取链接
        $req_params = [];
        $req_params['member_no'] = $lal_member_info['member_no'];
        $req_url = cdnurl('/api/Pay/findBank',true);
        write_log_record("[".date("Y-m-d H:i:s")."]查询绑定银行卡列表req_url：".$req_url);
        write_log_record("[".date("Y-m-d H:i:s")."]查询绑定银行卡列表参数：".json_encode($req_params,true));
        $result = send_request($req_url, $req_params,'GET'); 
        write_log_record("[".date("Y-m-d H:i:s")."]查询绑定银行卡列表结果：".json_encode($result,true));  
        if ($result && !empty($result)) {
            if ($result['data']['status'] == 'OK' && isset($result['data']['result']['bank_card_list']) && !empty($result['data']['result']['bank_card_list'])) {
                $bank_card_list = $result['data']['result']['bank_card_list'];
                if (count($bank_card_list) > 0) {
                    $insert_data = [];
                    $default_bank = [];
                    foreach ($bank_card_list as $key => $value) {
                        $exist_bank = $this->bank_model->where(['member_no'=>$lal_member_info['member_no']])->delete();
                        $data = [];
                        $data['member_no'] = $lal_member_info['member_no'];
                        $data['card_no'] = $value['card_no'];
                        $data['card_id'] = $value['card_id'];
                        $data['is_settle_card'] = $value['is_settle_card']?'1':'0';
                        $data['bank_code'] = $value['bank_code'];
                        $data['bank_name'] = $value['bank_name'];
                        $data['bind_time'] = $value['bind_time'];
                        $data['bank_account_prop'] = $value['bank_account_prop'] == 1?"1":"0";
                        $data['bank_provice'] = $value['bank_provice'];
                        $data['bank_city'] = $value['bank_city'];
                        $data['bank_contact_no'] = $value['bank_contact_no'];
                        $data['bank_contact_name'] = isset($value['bank_contact_name'])?$value['bank_contact_name']:'';
                        $data['bind_channel_code'] = $value['bind_channel_code'];
                        $data['createtime'] = time();
                        if ($data['is_settle_card'] == '1') {
                            $default_bank['bank'] = $data['bank_name'];
                            $default_bank['card'] = $data['card_no'];
                        }
                        $insert_data[] = $data;
                    }
                    Db::startTrans();
                    try {
                        if (count($insert_data)>0) {
                            $res = $this->bank_model->insertAll($insert_data);
                            if (false === $res) {
                                Db::rollback();
                                $this->error(__('No rows were inserted'));
                            }

                            if (count($default_bank) > 0) {
                                $res = $this->model->where(['id'=>$ids])->update($default_bank);
                                if (false === $res) {
                                    Db::rollback();
                                    $this->error(__('No rows were updated'));
                                }
                            }
                        }

                        $update_date = [];
                        //同步结余账户余额
                        $req_params = [];
                        $req_params['member_no'] = $lal_member_info['member_no'];
                        $req_params['account_type'] = '1000';
                        // $req_params['special_account_no'] = 'S005';
                        $req_url = cdnurl('/api/Pay/findBalance',true);
                        write_log_record("[".date("Y-m-d H:i:s")."]查询结余账户余额req_url：".$req_url);
                        write_log_record("[".date("Y-m-d H:i:s")."]查询结余账户余额参数：".json_encode($req_params,true));
                        $result = send_request($req_url, $req_params,'GET'); 
                        write_log_record("[".date("Y-m-d H:i:s")."]查询结余账户余额结果：".json_encode($result,true));  
                        if (!$result || empty($result) || $result['data']['status'] == 'ERROR') {
                            Db::rollback();
                            $this->error(__('No rows were updated'));
                        }
                        $abalance = $result['data']['result']['available_amount'];
                        $update_date['abalance'] = sprintf("%.2f",$abalance/100);

                        //同步佣金账户余额
                        $req_params['special_account_no'] = 'S005';
                        write_log_record("[".date("Y-m-d H:i:s")."]查询佣金账户余额req_url：".$req_url);
                        write_log_record("[".date("Y-m-d H:i:s")."]查询佣金账户余额参数：".json_encode($req_params,true));
                        $result = send_request($req_url, $req_params,'GET'); 
                        write_log_record("[".date("Y-m-d H:i:s")."]查询佣金账户余额结果：".json_encode($result,true));  
                        if (!$result || empty($result) || $result['data']['status'] == 'ERROR') {
                            Db::rollback();
                            $this->error(__('No rows were updated'));
                        }
                        $bbalance = $result['data']['result']['available_amount'];
                        $update_date['bbalance'] = sprintf("%.2f",$bbalance/100);

                        $res = $this->model->where(['id'=>$ids])->update($update_date);
                        if (false === $res) {
                            Db::rollback();
                            $this->error(__('No rows were updated'));
                        }

                        Db::commit();
                    }catch (ValidateException|PDOException|Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                }
            }
        }

        $this->success(__('Operation completed'));
    }

    public function getbankcardurl($ids = null)
    {
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $row = $this->model->find($ids);

        if (empty($row) || empty($row['member_no'])) {
            $this->error(__('No Results were found'));
        }

        //发送会员开户请求，获取链接
        $req_params = [];
        $req_params['member_no'] = $row['member_no'];
        $req_params['back_url'] = cdnurl('/api/member/syncBankCard',true);
        $req_url = cdnurl('/api/Pay/bankCard',true);
        write_log_record("[".date("Y-m-d H:i:s")."]会员绑卡相关页面req_url：".$req_url);
        write_log_record("[".date("Y-m-d H:i:s")."]会员绑卡相关页面参数：".json_encode($req_params,true));
        $result = send_request($req_url, $req_params,'GET'); 
        write_log_record("[".date("Y-m-d H:i:s")."]会员绑卡相关页面结果：".json_encode($result,true));  
        if ($result && !empty($result) && $result['data']['status'] == 'OK') {
            $update_date = [];
            $update_date['bank_card_url'] = $result['data']['result']['url']; 
            $res = $this->model->where('id',$ids)->update($update_date);
            $res?$this->success(__('Operation completed')):$this->error(__('Operation failed'));
        }else{
            $this->error(__('Operation failed'));
        }
    }
}
